// pages/firstpage/zanzhu/index.js
import {
  ApiRootUrl,IMG_PATH,apiList
} from '../../../config/index.js'
import Dialog from '../../../@vant/weapp/dialog/dialog';
import Toast from '../../../@vant/weapp/toast/toast';
import{
  request
} from "../../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    oldImg:'',
    img_l:[],
    isHasFujian:'已上传',
    fileList:[],
    needFujian:false,
    openId:'',
    userinfo:{},
    whcd:'',
    whcdCode:'',
    height:'',
    zzmm:'',
    zzmmCode:'',
    sfcb:'',
    cbqk:[],
    jjlxrxm:'',
    jjlxrsfz:'',
    ybrgx:'',
    ybrgxCode:'',
    isEdit:true,
    showIsCanbao:false,
    showCbqk:false,
    showZzmm:false,
    showYbrgx:false,
    showWhcd:false,
    nationShow: false,
    isCanbaoList:['是','否'],
    zzmmList:[
      {
        id:'13',
        text:'群众'
      },
      {
        id:'1',
        text:'中共党员'
      },
      {
        id:'3',
        text:'共青团员'
      },
      {
        id:'99',
        text:'其他'
      }
    ],
    ybrgxList:[
      {
      text: '父亲',
      id:'51'
    },
      {
      text: '母亲',
      id:'52'
    },
      {
      text: '儿子',
      id:'20'
    },
      {
      text: '女儿',
      id:'30'
    },
      {
      text: '妻子',
      id:'12'
    },
      {
      text: '丈夫',
      id:'11'
    },
      {
      text: '其他亲属',
      id:'97'
    },
      {
      text: '非亲属',
      id:'99'
    },
  ],
    result1List:[
      {text:'养老保险',id:'2'},
      {text:'医疗保险',id:'3'},
      {text:'失业保险',id:'4'},
      {text:'工伤保险',id:'5'},
      {text:'生育保险',id:'6'},
      {text:'农保保险',id:'7'},
    ],
    nation:'',
    result1:[],
    peopleInfo:{},
    whcdList:[
      {
        id:71,
        text:'初中'
      },
      {
        id:61,
        text:'高中'
      },
      {
        id:47,
        text:'技工学校'
      },
      {
        id:44,
        text:'职业高中'
      },
      {
        id:41,
        text:'中专'
      },
      {
        id:30,
        text:'大专在读'
      },
      {
        id:31,
        text:'大专毕业'
      },
      {
        id:20,
        text:'本科在读'
      },
      {
        id:21,
        text:'本科毕业'
      },
      {
        id:11,
        text:'博士'
      },
      {
        id:14,
        text:'硕士'
      },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
let userinfo=wx.getStorageSync('userinfo')
let openId=wx.getStorageSync('openId')
this.setData({
  userinfo:userinfo,
  openId:openId
})
this.queryFloatPeople()
  },
  
  upLoadImg(){
    let self = this;
    wx.chooseImage({
      count: 1,
      success(res){
        console.log('上传文件',res);
        self.setData({
          img_l: res.tempFilePaths
        })
        // if(res.tempFiles[0].size > 1024*1024*2){
        //   Toast.fail('上传文件大小最多不超过2M!');
        //   return;
        // }
        // let type = res.tempFiles[0].name.split(".")[1];
        // if(type !=='png' &&  type !=='jpg'){
        //   Toast.fail('照片格式错误!');
        //   return;
        // }
        Toast.loading({
          duration: 0,
          message: '加载中...',
          forbidClick: true,
        });
        // console.log(res.tempFilePaths[0].replace("http:","https:"));
        wx.uploadFile({
          url: ApiRootUrl + '/people/uploadPhoto', 
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData:{
            // openId:wx.getStorageSync('openId'),
            // oldPath:self.data.oldPath || ''
          },
          header: {
            "Content-Type": "multipart/form-data",
            'cookie': wx.getStorageSync("sessionid")
          },
          success(res) {
            Toast.clear();
            Toast.success('照片上传成功!');
            self.setData({
              isHasFujian:'已上传'
            })
          },
          fail(res) {
            Toast.clear();
            console.log(res)
            // Toast.fail(JSON.stringify(res));
            Toast({
              duration: 0,
              // forbidClick: true,
              type: 'fail',
              message: JSON.stringify(res),
              mask:'true'
            });
          }
        })
      }
    })
  },
  // afterRead(event) {
  //   let self=this
  //   const { file } = event.detail;
  //   // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  //   wx.uploadFile({
  //     url:ApiRootUrl + '/people/uploadPhoto', // 仅为示例，非真实的接口地址
  //     filePath: file.path,
  //     name: 'file',
  //     formData: {},
  //     success(res) {
  //       console.log(res);
  //       // 上传完成需要更新 fileList
  //       const  fileList = [] 
  //       fileList.push({ ...file, url: res.data });
  //       self.setData({ fileList },()=>{
  //         console.log(self.data.fileList);
  //       });
  //     },
  //   });
  // },
  queryFloatPeople(){
    wx.showLoading({
      title: '加载中。。。',
    })
    let info=this.data.userinfo
    let params={
      identity:info.identity
    }
    let self = this;
    wx.request({
      url: `${ApiRootUrl}/people/queryFloatPeople`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        if(res.data.code == 20000){
          wx.hideLoading({
            success: (res) => {},
          })
          let oldImg=res.data.data.base64
          if(oldImg&&oldImg.length){
            oldImg='data:image/png;base64,'+oldImg
            self.setData({
            oldImg:oldImg
          })
          }
          
          let info=res.data.data.tfloatPeopleDO

          if(info.whcd){
            self.data.whcdList.forEach(item=>{
              if(item.id==info.whcd){
                info.whcd=item.text
                self.setData({
                  whcd:item.text,
                  whcdCode:item.id
                })
                return
              }
            })
          }
          if(info.sg){
            self.setData({
              height:info.sg
            })
          }
          if(info.zzmm){
            self.data.zzmmList.forEach(item=>{
              if(item.id==info.zzmm){
                info.zzmm=item.text
                self.setData({
                  zzmm:item.text,
                  zzmmCode:item.id
                })
                return
              }
            })
          }
          if(info.sfcb){
            self.setData({
              sfcb:info.sfcb
            })
          }
          if(info.gxrname){
            self.setData({
              jjlxrxm:info.gxrname
            })
          }
          if(info.gxrcardid){
            self.setData({
              jjlxrsfz:info.gxrcardid
            })
          }
          if(info.ysqrgx){
            self.data.ybrgxList.forEach(item=>{
              if(item.id==info.ysqrgx){
                info.ysqrgx=item.text
                self.setData({
                  ybrgx:item.text,
                  ybrgxCode:item.id
                })
                return
              }
            })
          }
          if(info.cbqk){
            let str=''
            if(info.cbqk=='0000000'){
              str='暂无'
            }else{
              for(let i=0;i<info.cbqk.length;i++){
                if(info.cbqk.charAt(i)==1){
                  self.data.result1List.forEach(item=>{
                if(item.id==i+1){
                  str+=item.text+','
                }
            })
                }
                
              }
              let len=str.length-1
              str=str.substring(0,len)
            }
            info.cbqk=str
          }

          self.setData({
            peopleInfo:info
          })
        
        }else{
          wx.hideLoading({
            success: (res) => {},
          })
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res){
        wx.hideLoading({
          success: (res) => {},
        })
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  initXL() {
    let self = this;
    self.checkSessionMethod();
    let params = {
      dictionaryType: 'education'
    }
    let url = `${ApiRootUrl}/dictionaries/querytbDictionariesList`;
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    wx.request({
      url: url,
      method: 'get',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      parmas: params,
      data: params,
      success(res) {
        Toast.clear();
        if (res.data.code == 20000) {
          let qualificationsColumnsList = res.data.data;
          let qualificationsColumns = qualificationsColumnsList.map(value => value['dictionaryName']);
          // console.log("qualificationsColumns==>",qualificationsColumns)
          self.setData({
            qualificationsColumns: qualificationsColumns,
            qualificationsColumnsList: qualificationsColumnsList
          })
        } else {
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res) {
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  initMZ() {
    let self = this;
    let params = {
      dictionaryType: 'nation'
    }
    let url = `${ApiRootUrl}/dictionaries/querytbDictionariesList`;
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    wx.request({
      url: url,
      method: 'get',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      parmas: params,
      data: params,
      success(res) {
        Toast.clear();
        if (res.data.code == 20000) {
          let nationColumnsList = res.data.data;
          let nationColumns = nationColumnsList.map(value => value['dictionaryName']);
          self.setData({
            nationColumns: nationColumns,
            nationColumnsList: nationColumnsList
          })
        } else {
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res) {
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  nationClick() {
    this.initMZ();
    this.setData({
      nationShow: true
    })
  },
  nationConfirm(event) {
    console.log(event);
    this.setData({
      nation: event.detail.value,
      nationShow: false
    })
  },
  nationCancel() {
    this.setData({
      nationShow: false
    })
  },
  nationClose() {
    this.setData({
      nationShow: false
    })
  },
  onChangeLabel(event) {
    let self=this
    console.log('event0000----,',event);
    // var str=event.detail.join(';')
    // this.setData({
    //   result1: event.detail,
    //   cbqk:str
    // });
    let str=''
    event.detail.forEach(item=>{
      self.data.result1List.forEach(e=>{
        if(item==e.text){
          str+=e.id
        }
        return
      })
    })
    let newCbqk=['0','0','0','0','0','0','0']
    if(str&&str.length){
      
      for(var n=0;n<str.length;n++){
        let index= str.charAt(n)*1
        console.log(index);
        newCbqk[index-1]='1'
      }
    }
    console.log(newCbqk);
    let lastCbqk=''
    newCbqk.forEach(item=>{
      lastCbqk=lastCbqk+item
    })
    self.setData({
      result1: event.detail,
      cbqk:lastCbqk
    });
    console.log(self.data.cbqk);
  },
  editClick(){
    let self = this;
    let url = `${ApiRootUrl}/people/checkFloatPeople`;
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: url,
      method: 'GET',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      success(res){
        wx.hideLoading()
       
        if (res.data.code == 20000) {
          console.log("res====>",res)
          if(res.data.data.b==true){
            console.log(res.data.data.c);
              self.setData({
              isEdit:false,
              needFujian:res.data.data.c
              })
              if(res.data.data.c&&res.data.data.c==true){
                self.setData({
                  isHasFujian:'上传本人照片'
                  })
              }
    console.log(self.data.isEdit);
          }else{
            Toast({
              duration: 3000,
              forbidClick: true,
              type: 'fail',
              message:'您尚未入宿或已经提交暂住登记！',
              mask:true
            });
          }
        } else {
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
            mask:true
          });
        }
      },
      fail(res) {
        wx.hideLoading()
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
 
  },
  backEdit(){
    this.setData({
      isEdit:true
    })
  },
  showIsCanbao(){
    this.setData({
      showIsCanbao:true
    })
  },
  isCanbaoClose(){
    this.setData({
      showIsCanbao:false
    })
  },
  showZzmm(){
    this.setData({
      showZzmm:true
    })
  },
  zzmmClose(){
    this.setData({
      showZzmm:false
    })
  },
  zzmmCancel(){
    this.setData({
      showZzmm:false
    })
  },
  zzmmConfirm(e){
    console.log(e);
    this.setData({
      showZzmm:false,
      zzmm:e.detail.value.text,
      zzmmCode:e.detail.value.id,
    })
  },
  showYbrgx(){
    this.setData({
      showYbrgx:true
    })
  },
  ybrgxClose(){
    this.setData({
      showYbrgx:false
    })
  },
  ybrgxCancel(){
    this.setData({
      showYbrgx:false
    })
  },
  ybrgxConfirm(e){
    console.log(e);
    this.setData({
      showYbrgx:false,
      ybrgx:e.detail.value.text,
      ybrgxCode:e.detail.value.id
    })
  },
  showWhcd(){
    // this.initXL()
    this.setData({
      showWhcd:true
    })
  },
  whcdClose(){
    this.setData({
      showWhcd:false
    })
  },
  whcdCancel(){
    this.setData({
      showWhcd:false
    })
  },
  whcdConfirm(e){
    console.log(e);
    this.setData({
      showWhcd:false,
      whcd:e.detail.value.text,
      whcdCode:e.detail.value.id
    })
  },
  showCbqk(){
    this.setData({
      showCbqk:true
    })
  },
  cbqkClose(){
    this.setData({
      showCbqk:false
    })
  },
  isCanbaoCancel(){
    this.setData({
      showIsCanbao:false
    })
  },
  jjlxrxmBlur(event){
    console.log(event);
    this.setData({
      jjlxrxm: event.detail.value
    })
  },
  isCanbaoConfirm(e){
    console.log(e);
    this.setData({
      showIsCanbao:false,
      sfcb:e.detail.value
    })
  },
  checkIdentity(){
    Toast.loading({
      duration: 0,
      mask: true,
      message: '操作中...',
      forbidClick: true,
    });
    if(!this.data.jjlxrxm){
      Toast.clear()
      Toast.fail('请输入紧急联系人姓名')
      return
    }
    if(!this.data.jjlxrsfz){
      Toast.clear()
      Toast.fail('请输入紧急联系人身份证')
      return
    }
    return new Promise((reslove,reject)=>{
      let identifycode=this.data.jjlxrsfz.trim().toUpperCase()
      let params = {
        name:this.data.jjlxrxm.trim(),
        identity:identifycode,
      }
      request(apiList.checkByPerson,params).then(res =>{
        Toast.clear()
        reslove()
      }).catch(err => {
        Toast.clear()
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: err.message,
          mask:true
        });
      })
    })
  },
  submit(){
    console.log(this.data.jjlxrsfz,this.data.jjlxrsfz.length);
    if(this.data.jjlxrsfz&&this.data.jjlxrsfz.length){
      this.checkIdentity().then(_=>{
      console.log(this.data.type);
        this.submit1()         
    })
    }else{
      this.submit2()
    }
    
  },
  submit1(){
    console.log('点击提交');
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
    });
    // if(!this.data.nation){
    //   Toast.clear()
    //   Toast.fail('请选择民族')
    //   return
    // }
    // if(this.data.isHasFujian=='上传本人照片'){
    //   Toast.clear()
    //   Toast.fail('请上传照片')
    //   return
    // }
    // if(!this.data.whcd){
    //   Toast.clear()
    //   Toast.fail('请选择文化程度')
    //   return
    // }
    // if(!this.data.height){
    //   Toast.clear()
    //   Toast.fail('请输入身高')
    //   return
    // }
    // if(!this.data.zzmm){
    //   Toast.clear()
    //   Toast.fail('请选择政治面貌')
    //   return
    // }
    // if(!this.data.sfcb){
    //   Toast.clear()
    //   Toast.fail('请选择是否参保')
    //   return
    // }
    if(this.data.sfcb=='是'){
      if(!this.data.cbqk||!this.data.cbqk.length){
      Toast.clear()
      Toast.fail('请选择参保情况')
      return
      } 
    }
    // if(!this.data.jjlxrxm){
    //   Toast.clear()
    //   Toast.fail('请输入紧急联系人姓名')
    //   return
    // }
    // if(!this.data.jjlxrsfz){
    //   Toast.clear()
    //   Toast.fail('请输入紧急联系人身份证')
    //   return
    // }
    // if(!this.data.ybrgx){
    //   Toast.clear()
    //   Toast.fail('请选择与本人关系')
    //   return
    // }
    var jjlxrNum=this.data.jjlxrsfz
    let gxrsex=''
    let gxrcsrq=jjlxrNum.substring(6, 14)
    if (parseInt(jjlxrNum.substr(16, 1)) % 2 == 1) {
      gxrsex='1'
    }else{
      gxrsex="2"
    }
    let info=this.data.userinfo
    let identifycode=this.data.jjlxrsfz.trim().toUpperCase()
    let params={
      weixinopenid:this.data.openId,
      xm:info.name,
      gmsfhm:info.identity,
      // mz:this.data.nation,
      whcd:this.data.whcdCode,
      sg:this.data.height,
      zzmm:this.data.zzmmCode,
      sfcb:this.data.sfcb,
      cbqk:this.data.sfcb=='是'?this.data.cbqk:'0000000',
      gxrname:this.data.jjlxrxm,
      gxrcardid:identifycode,
      ysqrgx:this.data.ybrgxCode,
      gxrsex:gxrsex,
      gxrcsrq:gxrcsrq
    }
    let self = this;
    wx.request({
      url: `${ApiRootUrl}/people/updateFloatPeople`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        if(res.data.code == 20000){
          Toast.clear();
          Toast({
            type: 'success',
            duration: 3000,
            message: '提交成功',
          });
          setTimeout(()=>{
            wx.navigateBack()
          },3000) 
        }else{
          Toast.clear();
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res){
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  submit2(){
    console.log('点击提交');
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
    });
    // if(!this.data.nation){
    //   Toast.clear()
    //   Toast.fail('请选择民族')
    //   return
    // }
    // if(this.data.isHasFujian=='上传本人照片'){
    //   Toast.clear()
    //   Toast.fail('请上传照片')
    //   return
    // }
    // if(!this.data.whcd){
    //   Toast.clear()
    //   Toast.fail('请选择文化程度')
    //   return
    // }
    // if(!this.data.height){
    //   Toast.clear()
    //   Toast.fail('请输入身高')
    //   return
    // }
    // if(!this.data.zzmm){
    //   Toast.clear()
    //   Toast.fail('请选择政治面貌')
    //   return
    // }
    // if(!this.data.sfcb){
    //   Toast.clear()
    //   Toast.fail('请选择是否参保')
    //   return
    // }
    if(this.data.sfcb=='是'){
      if(!this.data.cbqk||!this.data.cbqk.length){
      Toast.clear()
      Toast.fail('请选择参保情况')
      return
      } 
    }
    // if(!this.data.jjlxrxm){
    //   Toast.clear()
    //   Toast.fail('请输入紧急联系人姓名')
    //   return
    // }
    // if(!this.data.jjlxrsfz){
    //   Toast.clear()
    //   Toast.fail('请输入紧急联系人身份证')
    //   return
    // }
    // if(!this.data.ybrgx){
    //   Toast.clear()
    //   Toast.fail('请选择与本人关系')
    //   return
    // }
    // if (parseInt(jjlxrNum.substr(16, 1)) % 2 == 1) {
    //   gxrsex='男'
    // }else{
    //   gxrsex="女"
    // }
    let info=this.data.userinfo
    // let identifycode=this.data.jjlxrsfz.trim().toUpperCase()
    let params={
      weixinopenid:this.data.openId,
      xm:info.name,
      gmsfhm:info.identity,
      // mz:this.data.nation,
      whcd:this.data.whcdCode,
      sg:this.data.height,
      zzmm:this.data.zzmmCode,
      sfcb:this.data.sfcb,
      cbqk:this.data.sfcb=='是'?this.data.cbqk:'0000000',
      gxrname:this.data.jjlxrxm,
      gxrcardid:'',
      ysqrgx:this.data.ybrgxCode,
      gxrsex:'',
      gxrcsrq:''
    }
    let self = this;
    wx.request({
      url: `${ApiRootUrl}/people/updateFloatPeople`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        if(res.data.code == 20000){
          Toast.clear();
          Toast({
            type: 'success',
            duration: 3000,
            message: '提交成功',
          });
          setTimeout(()=>{
            wx.navigateBack()
          },3000) 
        }else{
          Toast.clear();
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res){
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})